package com.smart.lab.view.activity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.smart.lab.R;
import com.smart.lab.databinding.ActivityClipBinding;
import com.smart.lab.model.CropPestDiseaseEntity;
import com.smart.lab.model.ResponseBean;
import com.smart.lab.utils.AppConstant;
import com.smart.lab.utils.MyUrls;
import com.smart.lab.utils.PhotoUtils;
import com.smart.lab.utils.net.ItheimaHttp;
import com.smart.lab.utils.net.listener.HttpResponseListener;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import okhttp3.ResponseBody;
import retrofit2.Call;

public class ClipActivity extends AppCompatActivity {

    ActivityClipBinding binding;

//    Intent intent = new Intent();
//            intent.putExtra(AppConstant.KEY.IMG_PATH, filePath);
//            intent.putExtra(AppConstant.KEY.PIC_WIDTH, width);
//            intent.putExtra(AppConstant.KEY.PIC_HEIGHT, height);

    String filePath;
    int width;
    int height;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityClipBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        filePath=getIntent().getStringExtra(AppConstant.KEY.IMG_PATH);
        width=getIntent().getIntExtra(AppConstant.KEY.PIC_WIDTH,0);
        height=getIntent().getIntExtra(AppConstant.KEY.PIC_HEIGHT,0);

        // Set the Toolbar as the ActionBar
        setSupportActionBar(binding.toolbar);

        // Enable the back button (home button) and set its visibility
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.back);

//        UCrop.of(sourceUri, destinationUri)
//                .withAspectRatio(16, 9)
//                .withMaxResultSize(maxWidth, maxHeight)
//                .start(context);

        UCrop.Options options=new UCrop.Options();
        options.setShowCropGrid(false);
        options.setHideBottomControls(true);



//        // 禁止UCrop自动调整图片大小以适应裁剪框
//        options.setFreeStyleCropEnabled(true);
//
//// 或者，如果您希望仍保留裁剪框，但内部图片按原始尺寸显示
//// 可以设置裁剪框的初始大小与图片大小一致，并禁止用户调整裁剪框大小
//        options.setAspectRatioOptions(0);



        UCrop.of(Uri.fromFile(new File(filePath)), Uri.fromFile(fileCropUri))
                .withAspectRatio(1, 1)
                .withMaxResultSize(299, 299)
                .withOptions(options)
                .start(this);

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        binding.upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //开始上传识别
            }
        });


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            final Uri resultUri = UCrop.getOutput(data);

            binding.image.setImageURI(resultUri);
            uploadClipPic(resultUri);
        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
        }
    }


    private void uploadClipPic(Uri uri){
        File file=new File(uri.getPath());
        List<File> fileList=new ArrayList<>();
        fileList.add(file);

        ItheimaHttp.uploadMultiFile(MyUrls.uploadPic1, null, fileList, new HttpResponseListener<ResponseBean<CropPestDiseaseEntity>>() {
            @Override
            public void onResponse(ResponseBean<CropPestDiseaseEntity> var1) {
                if (var1==null || var1.getData()==null){
                    Toast.makeText(ClipActivity.this,"未识别到虫害信息",Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }
                Intent intent=new Intent(ClipActivity.this,ScanResultActivity.class);
                intent.putExtra("entity",var1.getData());
                startActivity(intent);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable e) {
                super.onFailure(call, e);
            }
        });
    }

    private static final String TAG="ClIp";


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }



}
